﻿# -*- coding: utf-8 -*-
#!C:\Python31\python.exe
#FileName:Mainbackup.py
#python v3.1 for windows
import os
import time
import sys
import Ftpupload
import readcfg



#列出备份目录下所有文件路径，文件夹、文件名词。
#for dirpath,dirnames,filenames in backupdir:		
#	for dirname in dirnames:
#		print "dirpath is:" + dirpath
#		print "dirname is:" + dirname
#	for filename in filenames:
#		print "dirpath is:" + dirpath
#		print "filename with full path is:"+os.path.join(dirpath,filename)

#定义备份方法 [参数1 文件备份目录][参数2 源文件路径source[]是两个路径的数组 source[0],source[1]]
def backupd(backupdir,source):
	print ("++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
	print ("|==============     backup---file     ==================|")
	print ("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
	print (" ")
	if not os.path.exists(backupdir):		#判断备份目录是否存在，如果不存就创建一个。
		print (backupdir + " does not exists,will create a new !")
		print ("---------------------------------------------------------")
		os.mkdir(backupdir)
		print (":::::: Successfully created directory:" + backupdir + "::::::")
		print ("---------------------------------------------------------")
		
	today = time.strftime('%Y%m%d')		#取出当前年月日
	now = time.strftime('%H%M%S')		#取出当前时分秒
	yesterday = time.strftime('%Y%m%d',time.localtime(time.time() - 24*60*60)) # 取出昨天的时间
	target1 = today+'.7z'		# 定义今天压缩包生成的文件名。
	target2 = yesterday+'.7z'	# 定义昨天压缩包生成的文件名。
	bakname = backupdir+'\\'+target1 #备份文件的全路径 
	#判断自动生成一个以当天日期为名的文件夹
	# if not os.path.exists(backupdir+'/'+today):
		# print today+" directory does not exists,will create a new!"
		# print "---------------------------------------------------------"
		# os.mkdir(backupdir+'\'+today)
		# print ":::::: successflly created directory %s ::::::" % (today)
		# print "---------------------------------------------------------"
	for files in source:
		if os.path.isdir(files) == True:	# 判断备份源路径 path1 path2 是否存在
			zip_command="7z a %s %s %s" %(bakname,source[0],source[1]) # 如果目录存在，那么就指定要执行的打包命令。
		else:
			print (">>>>>"+files+"is not the Directory!")
			print (" ")
			print (">>>>>:::::: Backup Failed ::::::")
			sys.exit()
	if os.path.isfile(backupdir+'\\'+target2) == True:	# 判断昨天的备份文件是否存在 
		try:
			os.remove(backupdir+'\\'+target2) # 如果存在则删除
		except:
			print (">>>>>Failed to delete localhost old files")
			print (" ")
	else:
		print (">>>>>Localhost old file is not extis")
		print (" ")
	if os.system(zip_command) == 0: # 进行打包备份成功则提示备份成功，打包出现异常，则退出，备份失败。
		print (":::::: Successful backup! ::::::")
		print (" ")
		print ("Flie Path: " + backupdir + '\\' + target1)
		print (" ")
		Ftpupload.ftpupload((readcfg.Server),(readcfg.UserName),(readcfg.PassWord),(readcfg.Port)) # 调用Ftp上传的方法
	else:
		print (">>>>>:::::: Backup Failed ::::::")
		print (" ")
		sys.exit()
backupd((readcfg.backupdir),(readcfg.source))